package com.lhd.service;

import com.lhd.dao.TagDao;
import com.lhd.po.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by limi on 2017/10/16.
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Transactional
    @Override
    public Integer saveTag(Tag tag) {
        return tagDao.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagDao.findOne(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagDao.findByName(name);
    }

    @Transactional
    @Override
    public List<Tag> listTag(Integer page) {
        return tagDao.findAllByPage(page*10);
    }

    @Override
    public List<Tag> listTag() {
        return tagDao.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) { //1,2,3
        List<Long> idz = convertToList(ids);
        List<Tag> res = new ArrayList<>();
        for (Long id : idz){
            res.add(tagDao.findOne(id));
        }
        return res;
    }

    public List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for (int i=0; i < idarray.length;i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    public void clearBlogIdAndTagId(Long blogId) {
        tagDao.clearBlogIdAndTagId(blogId);
    }

    @Override
    public Long getCountByTagId(Long tagId) {
        return tagDao.getCountByTagId(tagId);
    }

    @Override
    public List<Tag> listTagTop(Integer i) {
        return tagDao.listTagTop(i);
    }


    @Transactional
    @Override
    public Integer updateTag(Long id, Tag tag) {

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("name",tag.getName());
        return tagDao.update(map);

//        Tag t = tagDao.findOne(id);
//        if (t == null) {
//            throw new NotFoundException("不存在该标签");
//        }
//        BeanUtils.copyProperties(tag,t);
//        return tagDao.save(t);
    }



    @Transactional
    @Override
    public Long deleteTag(Long id) {
        return tagDao.delete(id);
    }

    @Override
    public Integer countTag() {
        return tagDao.countTag();
    }

    @Override
    public void createBlogIdAndTagIds(Long blogId, List<Long> tagIds) {
        for (Long tagId:tagIds){
            tagDao.insertBlogIdAndTagId(blogId,tagId);
        }
    }
}
